﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoneImp {
	public class AnimationState {
		public AnimationStateData data;
		public Animation animation;
		public float time;
		bool loop;

		private Animation previous;
		private float previousTime;
		private bool previousLoop;
		private float mixTime;
		private float mixDuration;

		/* @param data May be 0 for no mixing. */
		public AnimationState(AnimationStateData data) {
			this.data = data;
		}

		public void update(float delta) {
			this.time += delta;
			this.previousTime += delta;
			this.mixTime += delta;
		}

		public void apply(SkeletonBase skeleton) {
			if (this.animation == null) return;
			
			if (this.previous != null) {
				this.previous.apply(skeleton, this.previousTime, this.previousLoop);
				float alpha = this.mixTime / this.mixDuration;
				if (alpha >= 1) {
					alpha = 1;
					this.previous = null;
				}
				this.animation.mix(skeleton, this.time, this.loop, alpha);
			} else
				this.animation.apply(skeleton, this.time, this.loop);
		}

		/* @param animationName May be 0. */
		public void setAnimationByName(string animationName, bool loop) {
			Animation animation = this.data.skeletonData.findAnimation(animationName);
			this.setAnimation(animation, loop);
		}

		/* @param animation May be 0. */
		void setAnimation(Animation newAnimation, bool loop) {
			this.previous = null;
			if (newAnimation != null && this.animation != null && this.data != null) {
				this.mixDuration = this.data.getMix(this.animation, newAnimation);
				if (this.mixDuration > 0) {
					this.mixTime = 0;
					this.previous = this.animation;
					this.previousTime = this.time;
					this.previousLoop = this.loop;
				}
			}
			this.animation = newAnimation;
			this.loop = loop;
			this.time = 0;
		}

	}
}
